import { useEffect } from "react";
import {
  Table,
  Card,
  Breadcrumb,
  Input,
  Space,
  Button,
  message,
  Select,
  ConfigProvider,
} from "antd";
import zh_CN from "antd/es/locale/zh_CN";
import { useHistory } from "react-router-dom";
import couponsApi from "../../api/coupons";
import { useCoupons } from "../../hook/coupons";
const { Search } = Input;
const { Option } = Select;
//显示一共多少条数据
function showTotal(total) {
  return `共 ${total} 条数据`;
}
//获取今天的日期
var day = new Date();
day.setTime(day.getTime());
var today = day.getFullYear() + "" + (day.getMonth() + 1) + "" + day.getDate();
// console.log(today);
// console.log(~~today);

// eslint-disable-next-line
export default () => {
  let history = useHistory();
  let [{ total, rows }, { getCoupons, setCouCurPage, setCouEachPage }] =
    useCoupons();
  // console.log(rows);
  //筛选过期优惠券
  const TimeOver = () => {
    let tes = rows.filter((item) => item.deadLine < today);
    console.log(tes);
    console.log("in");
    return tes;
  };
  //删除优惠券
  const deleteCoupon = async (e) => {
    if (e.target.nodeName === "SPAN") {
      let stuId =
        e.target.parentNode.parentNode.parentNode.children[0].textContent;
      const data = await couponsApi.delCoupon(stuId);
      if (data.deletedCount) {
        // 删除成功后再次获取后台数据
        getCoupons();
        message.success({
          content: "删除优惠券成功",
          duration: 0.5,
          onClose: () => {
            history.push("/info/coupons");
          },
        });
      }
    }
    return;
  };
  //修改优惠券信息
  const changeCoupon = async (e) => {
    if (e.target.nodeName === "SPAN") {
      let couId =
        e.target.parentNode.parentNode.parentNode.children[0].textContent;
      history.push(`/info/changeCoupon/${couId}`);
    }
    return;
  };
  //搜索优惠券
  //下拉选项
  let couType = "";
  function handleChange(value) {
    couType = value;
  }
  //输入框搜索事件
  const onSearch = async (value) => {
    let searchCon = {};
    TimeOver();
    if (value) {
      if (couType === "name") {
        searchCon[couType] = value;
      } else {
        searchCon[couType] = ~~value;
      }
      console.log(searchCon);
      const backData = await couponsApi.searchCoupon(searchCon);
      console.log(backData);
    }
    return;
  };
  //useEffect传一个数组准确的值，getCoupons改变useEffect才会调用
  useEffect(() => {
    getCoupons();
  }, [getCoupons]);
  const columns = [
    {
      title: "id",
      dataIndex: "_id",
      align: "center",
    },
    {
      title: "优惠券名称",
      dataIndex: "name",
      align: "center",
    },
    {
      title: "减免价格",
      dataIndex: "discount",
      align: "center",
    },
    {
      title: "减免需满足最小金额",
      dataIndex: "minMoney",
      align: "center",
    },
    {
      title: "优惠券截止日期",
      dataIndex: "deadLine",
      align: "center",
    },
    {
      title: "优惠券适用商品大类",
      dataIndex: `navsId`,
      align: "center",
      render: (text, record) => <span>{record.navsId.name}</span>,
    },
    {
      title: "操作",
      dataIndex: "operation",
      align: "center",
      render: () => (
        <>
          <Button
            type="primary"
            shape="round"
            style={{ marginRight: "5px" }}
            onClick={changeCoupon}
          >
            修改
          </Button>
          <Button type="primary" shape="round" danger onClick={deleteCoupon}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <div className="site-card-border-less-wrapper">
      <Space direction="vertical" style={{ width: "100%" }}>
        <Card>
          <Breadcrumb>
            <Breadcrumb.Item>主页</Breadcrumb.Item>
            <Breadcrumb.Item>优惠券</Breadcrumb.Item>
            <Breadcrumb.Item>
              <a href="#/info/coupons">优惠券列表</a>
            </Breadcrumb.Item>
          </Breadcrumb>
          <Space style={{ marginTop: "5px" }}>
            <Select
              defaultValue="请选择查询优惠券条目"
              style={{ width: 200 }}
              onChange={handleChange}
            >
              <Option key="name" value="name">
                优惠券名称
              </Option>
              <Option key="discount" value="discount">
                减免价格
              </Option>
              <Option key="minMoney" value="minMoney">
                减免需满足最小金额
              </Option>
              <Option key="deadLine" value="deadLine">
                优惠券截止日期
              </Option>
              {/* <Option key="navsId" value="navsId">
                优惠券适用商品大类
              </Option> */}
            </Select>
            <Search
              placeholder="请输入优惠券名称"
              onSearch={onSearch}
              enterButton
              style={{ width: "200px" }}
            />
          </Space>
        </Card>
        <Card>
          <ConfigProvider ConfigProvider locale={zh_CN}>
            <Table
              columns={columns}
              dataSource={rows}
              rowKey={(record) => record._id}
              pagination={{
                total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal,
                pageSizeOptions: [5, 10, 20, 50],
                defaultPageSize: 5,
                onChange: (page, pageSize) => {
                  setCouCurPage(page);
                  setCouEachPage(pageSize);
                },
              }}
            />
          </ConfigProvider>
        </Card>
      </Space>
    </div>
  );
};
